﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using vnFingerPrint.GUI;
using vnFingerPrint.DataAccess;
using vnCommon;
using System.IO;
using NeuralNetwork;
using System.Data.SqlClient;
using vnBiometricsSDK.FingerPrint;
using vnFingerPrint.SDK.Library;
using vnFingerPrint.BusinessObject;
using System.Threading;


namespace vnFingerPrint.GUI
{
    public partial class frmNeuralNetwork : Form
    {
        public frmNeuralNetwork()
        {
            InitializeComponent();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        int loaimang = 0;
        float heSoHoc = 0.0000001f;
        private void btnChonmang_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            frmChooseNetwork chooseNetwork = new frmChooseNetwork();
            chooseNetwork.ShowDialog();
            loaimang = chooseNetwork.Loaimang;
            heSoHoc = chooseNetwork.Hesohoc;
            btnChonmang.Enabled = false;
            pbTest.Visible = true;
            bwTrain.RunWorkerAsync();
            Cursor = Cursors.Default;
        }

        private void frmNeuralNetwork_Load(object sender, EventArgs e)
        {

        }
        Bitmap img_nhandang = null;
        private void btnNhandang_Click(object sender, EventArgs e)
        {
            btnNhandang.Enabled = false;
            Cursor = Cursors.WaitCursor;
            this.picAnhcannhandang.Image = null;
            pbVanTay.Image = null;
            lvResults.Items.Clear();
            pbTest.Value = 0;

            img_nhandang = vnCommonGUI.CommonFunction.OpenDialogImageFile();
            if (img_nhandang == null)
            {
                Cursor = Cursors.Default;
                btnNhandang.Enabled = true;
                return;
            }
            this.picAnhcannhandang.Image = (Bitmap)img_nhandang.Clone();
            bwTest.RunWorkerAsync();
            Cursor = Cursors.Default;
        }

        private void lvResults_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int id = int.Parse(lvResults.SelectedItems[0].ToolTipText);
                VanTay_Object vantay = VanTay_DataAccess.GetObject(id);
                string imgurl = Config_DataAccess.GetVanTayImagePath(vantay.ImgUrl);
                pbVanTay.Image = new Bitmap(imgurl);
            }
            catch { }
        }

        private void bwTest_DoWork(object sender, DoWorkEventArgs e)
        {
            string dactrung, Core;
            using (Bitmap newbmp = vnSumarySDK.CaiThienAnh(img_nhandang))
            {
                bwTest.ReportProgress(20);
                dactrung = vnSumarySDK.LayDacTrungString(newbmp, out Core);
            }

            float[] X = Helper.InputANN(Core, dactrung);
            bwTest.ReportProgress(40);
            //Thread.Sleep(300);
            DataTable da_Trongso = commonDatabase.GetSQLDataTable(clsConnectionString.GetConnectionString(), "SELECT So_CMND, Trongso, Daura,Id FROM dbo.Trongsomang");
            so_CMND = new SortedDictionary<float, string>();
            OK = false;
            int index = 0;
            foreach (DataRow row in da_Trongso.Rows)
            {
                string[] trongso = row["Trongso"].ToString().Split(new Char[] { ';' });
                float[] W = new float[trongso.Length];
                float Y = 0.0f;
                for (int i = 0; i < trongso.Length; i++)
                {
                    W[i] = float.Parse(trongso[i]);
                }

                if (trongso.Length == 16)
                {

                    for (int i = 0; i < X.Length; i++)
                    {
                        Y += X[i] * W[i];
                    }
                }
                else
                {
                    Y = BackProNeuralAlg.GetInstance().Test(W, X)[0];
                }

                string strDR = row["Daura"].ToString();
                float daura = float.Parse(strDR);

                if (Math.Abs(daura - Y) <= 20)
                {
                    so_CMND.Add((float)Math.Round((double)Math.Abs(daura - Y), 3), row["So_CMND"].ToString() + " @ " + row["Id"]);
                    OK = true;
                }
                index++;
                int p =40+ index * 60 / da_Trongso.Rows.Count;
                bwTest.ReportProgress(p);
            }
            
        }

        private void bwTest_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbTest.Value = e.ProgressPercentage;
        }

        private void bwTest_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (OK)
            {
                lvResults.LargeImageList = new ImageList();
                lvResults.LargeImageList.ImageSize = new Size(100, 100);
                foreach (KeyValuePair<float, string> s in so_CMND)
                {
                    CongDan_Object obj = CongDan_DataAccess.GetObject(s.Value.Substring(0, s.Value.IndexOf('@')));
                    ListViewItem lvit = new ListViewItem("Họ và tên: " + obj.HoTen + "\nSai lech:" + s.Key, obj.SoCMND);
                    lvit.ToolTipText = s.Value.Substring(s.Value.IndexOf('@') + 1);
                    string imgurl = Config_DataAccess.GetCongDanImagePath(obj.ImageUrl);
                    try
                    {
                        if (obj.ImageUrl != "" && obj.ImageUrl != null) lvResults.LargeImageList.Images.Add(obj.SoCMND, new Bitmap(imgurl));
                        else lvResults.LargeImageList.Images.Add(obj.SoCMND, new Bitmap(512, 512));
                    }
                    catch
                    {
                    }
                    lvResults.Items.Add(lvit);
                }
            }
            else
            {
                MessageBox.Show("Không tìm thấy trong cơ sở dữ liệu");
            }
            btnNhandang.Enabled = true;
        }

        public SortedDictionary<float, string> so_CMND { get; set; }
        public bool OK = false;

        private void bwTrain_DoWork(object sender, DoWorkEventArgs e)
        {
            int index = 0;
            if (loaimang == 0)
            {
                commonDatabase.ExecuteNonQuerySQL(clsConnectionString.GetConnectionString(), "TRUNCATE TABLE dbo.Trongsomang");
                DataTable da = commonDatabase.GetSQLDataTable(clsConnectionString.GetConnectionString(), "SELECT So_CMND, Dactrung,CoreDelta,Id FROM dbo.Vantay");
                foreach (DataRow row in da.Rows)
                {
                    string dactrung = row["DacTrung"].ToString();
                    string cores = row["CoreDelta"].ToString();
                    float[] X = Helper.InputANN(cores, dactrung);
                    SinglePerceptron singlePerceptron = new SinglePerceptron(X, heSoHoc);
                    singlePerceptron.Learning_Network();

                    float[] end_W = singlePerceptron.W;
                    float end_Y = singlePerceptron.Y;

                    string strW = "";
                    for (int i = 0; i <= end_W.Length - 2; i++)
                    {
                        strW += end_W[i].ToString() + ";";
                    }
                    strW += end_W[end_W.Length - 1].ToString();
                    string strSo_CMND = row["So_CMND"].ToString();

                    commonDatabase.ExecuteNonQuerySQL(clsConnectionString.GetConnectionString(), "INSERT INTO dbo.Trongsomang([So_CMND],[daura],[trongso],[Id]) VALUES('" + strSo_CMND + "','" + end_Y.ToString() + "','" + strW + "','" + row["Id"] + "')");
                    index++;
                    bwTrain.ReportProgress(index*100/da.Rows.Count);
                }
            }
            else
            {
                commonDatabase.ExecuteNonQuerySQL(clsConnectionString.GetConnectionString(), "TRUNCATE TABLE dbo.Trongsomang");
                DataTable da = commonDatabase.GetSQLDataTable(clsConnectionString.GetConnectionString(), "SELECT So_CMND, Dactrung,CoreDelta,Id FROM dbo.Vantay");
                foreach (DataRow row in da.Rows)
                {
                    string dactrung = row["DacTrung"].ToString();
                    string cores = row["CoreDelta"].ToString();
                    float[] X = Helper.InputANN(cores, dactrung);


                    float[] end_W = BackProNeuralAlg.GetInstance().Training(X);
                    float end_Y = BackProNeuralAlg.GetInstance().Test(end_W, X)[0];

                    string strW = "";
                    for (int i = 0; i <= end_W.Length - 2; i++)
                    {
                        strW += end_W[i].ToString() + ";";
                    }
                    strW += end_W[end_W.Length - 1].ToString();
                    string strSo_CMND = row["So_CMND"].ToString();

                    commonDatabase.ExecuteNonQuerySQL(clsConnectionString.GetConnectionString(), "INSERT INTO dbo.Trongsomang([So_CMND],[daura],[trongso],[Id]) VALUES('" + strSo_CMND + "','" + end_Y.ToString() + "','" + strW + "','" + row["Id"] + "')");
                    index++;
                    bwTrain.ReportProgress(index * 100 / da.Rows.Count);
                }
            }
        }

        private void bwTrain_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbTest.Value = e.ProgressPercentage;
        }

        private void bwTrain_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnChonmang.Enabled = true;
            pbTest.Visible = false;
            MessageBox.Show("Training thanh coong !");
        }
    }
}
